<template>
  <div class="search-view">
    <!-- 搜索头部 -->
    <el-card class="search-header">
      <div class="search-info">
        <h1>
          <el-icon><Search /></el-icon>
          搜索结果
        </h1>
        <div class="search-input">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文章..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>
      <p class="result-info" v-if="searchKeyword">
        找到 {{ total }} 篇与 "{{ searchKeyword }}" 相关的文章
      </p>
    </el-card>

    <!-- 搜索过滤器 -->
    <el-card class="search-filter">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="排序">
          <el-select v-model="filterForm.sort" @change="handleFilterChange">
            <el-option label="最新发布" value="time" />
            <el-option label="最多阅读" value="views" />
            <el-option label="最多评论" value="comments" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-select v-model="filterForm.timeRange" @change="handleFilterChange">
            <el-option label="全部时间" value="all" />
            <el-option label="最近一周" value="week" />
            <el-option label="最近一月" value="month" />
            <el-option label="最近一年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="filterForm.category" @change="handleFilterChange">
            <el-option label="全部分类" value="" />
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 搜索结果列表 -->
    <el-card v-loading="loading" class="search-results">
      <template v-if="blogs.length">
        <blog-list :blogs="blogs" />
      </template>
      <el-empty
        v-else-if="!loading"
        :description="
          searchKeyword
            ? `未找到与 "${searchKeyword}" 相关的文章`
            : '请输入关键词搜索'
        "
      />
      
      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useBlogStore } from '@/stores/blog'
import BlogList from '@/components/blog/BlogList.vue'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()

// 状态
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const filterForm = ref({
  sort: 'time',
  timeRange: 'all',
  category: ''
})

// 分类数据
const categories = ref([
  { label: '技术', value: 'tech' },
  { label: '生活', value: 'life' },
  { label: '随笔', value: 'essay' },
  { label: '其他', value: 'other' }
])

// 计算属性
const blogs = computed(() => blogStore.blogs)

// 方法
const fetchSearchResults = async () => {
  if (!searchKeyword.value.trim()) return
  
  loading.value = true
  try {
    await blogStore.fetchBlogs({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchKeyword.value,
      ...filterForm.value
    })
    total.value = blogStore.total
  } catch (error) {
    console.error('Failed to fetch search results:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  updateRoute()
}

const handleFilterChange = () => {
  currentPage.value = 1
  updateRoute()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  updateRoute()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  updateRoute()
}

const updateRoute = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  router.push({
    path: '/search',
    query: {
      q: searchKeyword.value,
      page: currentPage.value.toString(),
      size: pageSize.value.toString(),
      sort: filterForm.value.sort,
      time: filterForm.value.timeRange,
      category: filterForm.value.category
    }
  })
}

// 从路由参数中恢复搜索状态
const restoreSearchState = () => {
  const query = route.query
  searchKeyword.value = query.q as string || ''
  currentPage.value = Number(query.page) || 1
  pageSize.value = Number(query.size) || 10
  filterForm.value.sort = query.sort as string || 'time'
  filterForm.value.timeRange = query.time as string || 'all'
  filterForm.value.category = query.category as string || ''
}

// 监听路由变化
watch(
  () => route.query,
  () => {
    restoreSearchState()
    if (searchKeyword.value) {
      fetchSearchResults()
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.search-view {
  .search-header {
    margin-bottom: 20px;
    
    .search-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
      
      h1 {
        margin: 0;
        font-size: 24px;
        display: flex;
        align-items: center;
        gap: 10px;
        
        .el-icon {
          font-size: 24px;
          color: $primary-color;
        }
      }
      
      .search-input {
        width: 400px;
      }
    }
    
    .result-info {
      margin: 0;
      color: $text-secondary;
    }
  }
  
  .search-filter {
    margin-bottom: 20px;
    
    :deep(.el-form) {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  
  .search-results {
    min-height: 400px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

// 响应式布局
@media (max-width: $breakpoint-sm) {
  .search-view {
    .search-header {
      .search-info {
        flex-direction: column;
        align-items: stretch;
        gap: 15px;
        
        .search-input {
          width: 100%;
        }
      }
    }
    
    .search-filter {
      :deep(.el-form) {
        .el-form-item {
          width: 100%;
          
          .el-form-item__content {
            width: 100%;
            
            .el-select {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style> 